package com.skytech.component.monitor.enterprise_data_monitoring;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.FormateConnection;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class GuangDongService implements CrawlerScript {


    private static final Logger log = LoggerFactory.getLogger(GuangDongService.class);
    private static final String province = "广东";

    @Autowired
    private ChromeBrowser chromeBrowser;
    @Autowired
    private SaveDataUtil saveDataUtil;

    @Override
    public void start() {
        int year = LocalDate.now().getYear();

        int i = 1;
        Document document = null;
        do {
            String url = "https://app.gdep.gov.cn/epinfo/region/0/" + i;
            Document documentNew = null;
            try {
                documentNew = FormateConnection.createConnection(Jsoup.connect(url))
                        .data("year", year + "")
                        .ignoreContentType(true)
                        .post();
                log.info("当前页面--{}", url);
            } catch (Exception e) {
                log.error(e.getMessage());
                continue;
            }
            if (document != null) {
                if (document.equals(documentNew)) {
                    log.info("广东数据爬取结束");
                    return;
                }
            }
            document = documentNew;
            JSONObject jsonObject = JSONObject.parseObject(documentNew.getElementsByTag("body").text());
            JSONArray jsonArray = jsonObject.getJSONArray("listDirectinfoVo");
            ChromeDriver driver = chromeBrowser.getChromeDriver();
            for (Object o : jsonArray) {
                JSONObject json = JSONObject.parseObject(o.toString());
                String urlSon = "https://app.gdep.gov.cn/epinfo/selfmonitor/getEnterpriseInfo/" + json.getString("monitorDirectId") + "?ename=" + json.getString("entername") + "&year=" + year;


                try {
                  /*  documentNew = FormateConnection.createConnection(Jsoup.connect(urlSon))
                            .get();*/

                    driver.get(urlSon);
                    driver.findElementByXPath("//*[@id='SelfmonitorMonitor']").click();
                    log.info("当前页面--{}", urlSon);
                    Thread.sleep(3000);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                Elements elements = parse.getAllElements();
                //todo
                //option中的值获取不到

                List<String> monitorPoints = new ArrayList<>();
                List<String> monitorInfos = new ArrayList<>();

                driver.findElementByXPath("//*[@id='Business-one']/div/div/div[2]/table[1]/tbody/tr[1]/td[4]/select").click();
                List<WebElement> monitorPointList = driver.findElementsByCssSelector("#Business-one > div > div > div.widget-content > table.talbo > tbody > tr:nth-child(1) > td:nth-child(4) > select > option");
                driver.findElementByXPath("//*[@id='Business-one']/div/div/div[2]/table[1]/tbody/tr[1]/td[6]/select").click();
                List<WebElement> monitorInfoList = driver.findElementsByCssSelector("#Business-one > div > div > div.widget-content > table.talbo > tbody > tr:nth-child(1) > td:nth-child(6) > select > option");
                elements.select("#Business-one > div > div > div.widget-content > table.talbo > tbody > tr:nth-child(1) > td:nth-child(4) > select > option").forEach(l -> {
                    String point = l.text();
                    monitorPoints.add(point);
                });
                elements.select("#Business-one > div > div > div.widget-content > table.talbo > tbody > tr:nth-child(1) > td:nth-child(6) > select > option").forEach(l -> {
                    String info = l.text();
                    monitorInfos.add(info);
                });
                List<MonitorData> monitorDataList = new ArrayList<>();
                for (int j = 0; j < monitorPointList.size(); j++) {
                    monitorPointList.get(j).click();
                    for (int k = 0; k < monitorInfoList.size(); k++) {
                        // Document documentTmp = null;
                        try {
                            monitorInfoList = driver.findElementsByCssSelector("#Business-one > div > div > div.widget-content > table.talbo > tbody > tr:nth-child(1) > td:nth-child(6) > select > option");
                            monitorInfoList.get(k).click();
                            driver.findElementByXPath("//*[@id='indate']").click();
                            driver.findElementByXPath("//*[@id='jedatebox']/div[3]/div/span[2]").click();
                            driver.findElementByXPath("//*[@id='dateinfo']").click();
                            driver.findElementByXPath("//*[@id='jedatebox']/div[3]/div/span[2]").click();
                            driver.findElementByXPath("//*[@id='butbut']").click();
                            Thread.sleep(3000);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                        partClickNext(driver, monitorDataList, json, monitorPoints.get(j), monitorInfos.get(k), null);

                    }
                }
                saveDataUtil.saveTag(monitorDataList, province);

            }
            driver.quit();
            i++;
        } while (true);


    }

    private void partClickNext(ChromeDriver driver, List<MonitorData> monitorDataList, JSONObject json, String point, String info, String html) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parseNew = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        Elements elements = parseNew.getAllElements();
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        if (!elements.select("#onitoring tr").isEmpty() && !elements.select("#onitoring tr").text().equals("没有数据")) {
            elements.select("#onitoring tr").forEach(l -> {
                MonitorData monitorData = new MonitorData();
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setCompanyName(json.getString("entername"));
                monitorData.setProvince(province);
                monitorData.setArea(json.getString("areaName"));
                monitorData.setPollutionType(json.getString("entertypename"));
                monitorData.setMonitorPoint(point);
                monitorData.setMonitorInfo(info);
                monitorData.setMonitorTime(l.getElementsByTag("td").get(0).text() + " " + l.getElementsByTag("td").get(1).text());
                monitorData.setMonitorValue(l.getElementsByTag("td").get(2).text());
                monitorData.setMonitorStandardValue(l.getElementsByTag("td").get(4).text());
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);
            });
        }
        try {
            driver.findElementByXPath("//*[@id='Business-one']/div/div/div[2]/div/a[text()='下一页']").click();
        } catch (Exception e) {
            log.error(e.getMessage());
            return;
        }

        partClickNext(driver, monitorDataList, json, point, info, html);
    }


}
